<template>
  <!-- page: CreatePost -->
  <div class = "create-post-page">
    <h4 class = "text-center">{{isEditMode ? '编辑文章' : '新建文章'}}</h4>
    <Uploader
      class = "d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      action = "/upload"
      v-bind:beforeUpload="uploadCheck"
      v-on:file-uploaded="handleFileUploaded"
      v-bind:uploaded="uploadedData"
    >
      <h2>点击上传图片</h2>
      <template #loading>
        <div class = "d-flex">
          <div class = "spinner-border text-secondary" role = "status">
            <span class = "sr-only">Loading ...</span>
          </div>
          <h2>正在上传 ...</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img v-bind:src="dataProps.uploadedData.data.url">
      </template>
    </Uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class = "mb-3">
        <label class = "form-label">文章标题：</label>
        <validate-input
          type = "text"
          placeholder = "请输入文章标题"
          :rules="titleRules" v-model="titleVal"
        />
      </div>
      <div class = "mb-3">
        <label class = "form-label">文章详情：</label>
        <validate-input
          type = "text"
          tag = "textarea"
          rows = "10"
          placeholder = "请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class = "btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
// 导入 vuex
import { useStore } from 'vuex'
// 导入 vue-router
import { useRouter, useRoute } from 'vue-router'
// 导入 组件
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import Uploader from '@/components/Uploader.vue'
// 导入 上传图片规则
import { beforeUploadCheck } from '@/assets/js/helper'
// 导入 数据
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '@/assets/js/store'
// 导入 消息提示
import createMessage from '@/assets/js/createMessage'

// 对setup函数进行封装，返回options的对象
export default defineComponent({
  // 页面名称
  name: 'CreatePost',
  // 注册组件
  components: {
    ValidateInput,
    ValidateForm,
    Uploader
  },

  // 组合式api入口
  setup () {
    const titleVal = ref('')
    const router = useRouter()
    const route = useRoute()
    // 泛型
    const store = useStore<GlobalDataProps>()
    // 图片Id
    let imageId = ''
    // 上传文件数据
    const uploadedData = ref()
    // 文章Id
    const isEditMode = !!route.query.id
    // 邮箱验证
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    // 文章详情验证
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    onMounted(() => {
      // 编辑文章
      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          // 获取 当前文章数据
          const currentPost = rawData.data
          // 获取 当前文章图片
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          // 获取 当前文章标题
          titleVal.value = currentPost.title
          // 获取 当前文章详情
          contentVal.value = currentPost.content || ''
        })
      }
    })
    // 获取 上传图片Id
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }
    // 创建文章
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            // _id: new Date().getTime() + '',
            author: _id,
            title: titleVal.value,
            content: contentVal.value,
            column
            // createdAt: new Date().toLocaleString()
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? { id: route.query.id, payload: newPost } : newPost
          // 发送文章相关数据, 跳转页面
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功, 2秒后跳转至该文章', 'success', 2000)
            setTimeout(() => {
              // 跳转页面
              router.push({ name: 'column', params: { id: column } })
            }, 2000)
          })
        }
      }
    }
    // 上传图片
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
      const { passed, error } = result
      if (error === 'format') {
        createMessage('上传的图片格式只能是 JPG/PNG 格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传的图片大小不能超过 1Mb', 'error')
      }
      return passed
    }
    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      uploadCheck,
      handleFileUploaded,
      uploadedData,
      isEditMode
    }
  }
})
</script>

<style lang="css">
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
